/**
 * 
 */
package com.ttl.common.util;

import java.util.ArrayList;
import java.util.Date;


import javax.servlet.http.HttpServletRequest;

import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *  @author :  Surasak Lekmart
 *  Created :  26 Jun 2012 17:11:52 
 *  Project :  ittl
 */
public class MethodUtils {

	public static boolean showPage(HttpServletRequest request, String hql, SessionFactory sessionFactory) {
		
		int pageNumber = 1;
		int maxEntriesPerPage = 20;
		int lineNumber = 1;
		
		try {pageNumber = Integer.parseInt(request.getParameter("page"));} catch (Exception e) {}
		
		if(request.getParameter("maxEntriesPerPage")!=null){maxEntriesPerPage = Integer.parseInt(request.getParameter("maxEntriesPerPage"));}
		
		if(request.getParameter("lineNumber")!=null) {
			request.setAttribute("lineNumber", request.getParameter("lineNumber"));
		}else {
			request.setAttribute("lineNumber", lineNumber);
		}
		
		Page page = getResultsPage(hql, pageNumber, maxEntriesPerPage, sessionFactory);
		
		return setAttributeOfRequest(request, page);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static Page getResultsPage(String hql, int pageNumber,
			int maxEntriesPerPage, SessionFactory sessionFactory) {
		Page page = new Page();
		
		ArrayList result = new ArrayList();
		
		long before = new Date().getTime();
		Session session = null;

		try {
			//SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();
			
			// ลำดับข้อมูลที่จะให้แสดงผล เช่น 0-100
			int offset = (pageNumber-1)*maxEntriesPerPage;
			
			Query q = session.createQuery(hql);
			
			ScrollableResults scr = q.scroll();
			// ตรวจสอบก่อนว่าค้นหาเจอหรือไม่ (ถ้าเจอจะได้ ค่า RowNumber ที่ rec สุดท้ายมากกว่า -1
			scr.last();
			
			if(scr.getRowNumber()>-1) {
				scr.first();
				scr.scroll(offset);
				
				int i=0;
				while (maxEntriesPerPage>i++) {
					result.add(scr.get(0));
					if(!scr.next()) {
						break;
					}					
				}
				scr.last();
				page.setAllElement(scr.getRowNumber()+1);
				page.setCurrentPage(pageNumber);
				page.setMaxEntriesPerPage(maxEntriesPerPage);
				page.setResultList(result);
			}
			session.getTransaction().commit();
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}finally {
			session.close();
		}
		long after = new Date().getTime();
		double resultTime = (after-before)/1000d;
		System.out.println("resultTime: "+resultTime+" second");
		
		return page;
	}

	private static boolean setAttributeOfRequest(HttpServletRequest request,
			Page page) {
		request.setAttribute("maxEntriesPerPage", page.getMaxEntriesPerPage());
		request.setAttribute("allElement", page.getAllElement());
		
		if (page!=null && page.getAllElement()>0) {
			request.setAttribute("itemResults", page.getResultList());
			request.setAttribute("offset", (page.getCurrentPage()-1)*page.getMaxEntriesPerPage());
			request.setAttribute("currentPage", page.getCurrentPage());
			
			if (page.isNextPage()==true) {	request.setAttribute("nextPage", page.getCurrentPage()+1);	}
			if (page.isPreviousPage()==true) {	request.setAttribute("previousPage", page.getCurrentPage()-1);	}
			if (page.isFirstPage()==true) {	request.setAttribute("firstPage", 1);	}
			if (page.isLastPage()==true && page.getMaxEntriesPerPage()!=0) {
				if (page.getAllElement()%page.getMaxEntriesPerPage()==0) {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage());
				}else {
					request.setAttribute("lastPage", page.getAllElement()/page.getMaxEntriesPerPage()+1);
				}
			}
			return true;
		}else {
			return false;
		}
	}
}
